<template>
    <div>
        <el-card>
            <el-page-header content="用户列表" icon="" title="用户管理"></el-page-header>
            <el-table :data="tableData" height='600px' style="width: 100%">
                <el-table-column prop="username" label="用户名" width="100"></el-table-column>
                <el-table-column  prop="avatar" label="头像" width="100">
                    <template  #default="scope">
                        <img class="the_img" :src="scope.row.avatar?scope.row.avatar:'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'">
                    </template>
                </el-table-column>
                <el-table-column prop="role" label="角色" width="90">
                    <template #default="scope">
                        <el-tag v-if="scope.row.role===1" type="success">超级管理员</el-tag>   
                        <el-tag v-else>管理员</el-tag>   
                    </template>
                </el-table-column>
                <el-table-column prop="introduction" label="个人简介" ></el-table-column>
                <el-table-column prop="address" label="操作" width="150">
                    <template #default="scope">
                        <el-button size="small"  @click="handleEdit(scope.$index,scope.row)"
                        >编辑</el-button>
                        <el-popconfirm title="你确定要删除吗?" confirm-button-text="确定" cancel-button-text="取消"
                        @confirm="handleDelete(scope.row)">
                            <template #reference>
                                <el-button size="small" type="danger">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <el-dialog
        title="修改用户"
        v-model="dialogVisible"
        width="30%"
        >
            <el-form
            :model="userForm"
            :rules="userFormRules"
            ref="userFormRef"
            label-width="80px"
            >
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="userForm.username"></el-input>
                </el-form-item>
                <el-form-item label="头像">
                    <div class="box-card">
                        <img class="the_img" :src="userForm.avatar" alt="">
                        <div class="btn-box">
                            <input type="file" accept="image/*" style="display: none" id="iptRef" @change="onFileChange" />
                            <el-button type="primary" icon="el-icon-plus" @click="chooseImg">选择图片</el-button> 
                        </div>
                    </div>
                </el-form-item> 
                <el-form-item label="密码" prop="password">
                    <el-input type="password" v-model="userForm.password"></el-input>
                </el-form-item>
                <el-form-item label="角色" prop="role">
                    <el-select v-model="userForm.role" placeholder="请选择权限" style="width:100%">
                        <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="简介" prop="introduction">
                    <el-input v-model="userForm.introduction" type="textarea" :rows="2" placeholder="请输入内容"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click='handleEditConfirm()'>确 定</el-button>
                </span>
            </template>
        </el-dialog>

        
    </div>
</template>

<script setup>
import {ref,onMounted,reactive} from 'vue'
import {ElMessage} from 'element-plus'
import {allUserAPI,deleteUserAPI,editUserAPI} from '@/api'

const userFormRef=ref()
let userForm=reactive({
    username:'',
    password:'',
    role:'', //1 管理员   2 编辑
    introduction:' ',
    id:'',
    avatar:''
})
// 权限选择
const options=[
    {label:'超级管理员',value:1},
    {label:'管理员',value:2},
]
const userFormRules=reactive({
    username: [
      { required: true, message: '请输入姓名', trigger: 'blur' },
      { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'},
    ],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
    introduction: [{ required: true, message: '请输入简介', trigger: 'blur' }],
    role: [{ required: true, message: '请权限权限', trigger: 'blur' }]
})
const tableData=ref([])
onMounted(()=>{
    getAllUser()
})
// 获取全部用户信息
const getAllUser=async()=>{
    const {data:res}=await allUserAPI()
    if(res.status===0) tableData.value=res.userinfo
}

// 删除按钮
const handleDelete=async (row)=>{
    const {data:res}=await deleteUserAPI(row.id)
    if(res.status===0){
        ElMessage.success('删除成功')
        return getAllUser()
    }else{
        return ElMessage.error('删除失败')
    }
}

const dialogVisible=ref(false)
// 编辑按钮
const handleEdit=(index,row)=>{
    dialogVisible.value=true
    userForm=row    
}
// 编辑确认按钮
const handleEditConfirm=()=>{
    userFormRef.value.validate(async valid=>{
        if(valid){
            const {data:res}=await editUserAPI(userForm)
            if (res.status !== 0 ) {
                ElMessage.error('更新失败');
                return
            }
            ElMessage.success('更新成功')
            dialogVisible.value=false
            console.log("编辑",res)
        }
    })
}

// 编辑图片
const chooseImg=function () {
    // 模拟点击行为
    document.getElementById('iptRef').click()
  }
const onFileChange=function (e) {
    const files = e.target.files // 拿到用户选择的文件数组
    console.log(files);
    if (files.length === 0) {
     
    } else {
      // 解决方案2：文件->base64字符串（此字符串是可以发给后台的）
      const fr = new FileReader()
      fr.readAsDataURL(files[0]) // 传入文件对象开始读
      fr.onload = (e) => { 
        userForm.avatar = e.target.result // 赋予给变量，让他显示在img的src里
      }
    }
  }
</script>

<style lang="scss" scoped>
.el-table{
    margin-top:50px
}
 
.the_img{
    width: 50px;
    height: 50px;
}
</style>
